/**
 * jqPagination adapter for bsgrid.
 *
 * jQuery.bsgrid v1.37 by @Baishui2004
 * Copyright 2014 Apache v2 License
 * https://github.com/baishui2004/jquery.bsgrid
 */
/**
 * require common.js, grid.js.
 *
 * @author Baishui2004
 * @Date August 31, 2014
 */
//$.fn.bsgrid.getCurPage = function (options) {
//    return $('#' + options.pagingId + ' input').data('current-page');
//};
//
//$.fn.bsgrid.refreshPage = function (options) {
//    $.fn.bsgrid.getGridObj(options.gridId).page($.fn.bsgrid.getCurPage(options));
//};
//
//$.fn.bsgrid.firstPage = function (options) {
//    $('#' + options.pagingId + ' a.first').click();
//};
//
//$.fn.bsgrid.prevPage = function (options) {
//    $('#' + options.pagingId + ' a.previous').click();
//};
//
//$.fn.bsgrid.nextPage = function (options) {
//    $('#' + options.pagingId + ' a.next').click();
//};
//
//$.fn.bsgrid.lastPage = function (options) {
//    $('#' + options.pagingId + ' a.last').click();
//};
//
//$.fn.bsgrid.gotoPage = function (options, goPage) {
//    if (goPage == undefined) {
//        return;
//    }
//    if ($.trim(goPage) == '' || isNaN(goPage)) {
//        if (options.settings.pageIncorrectTurnAlert) {
//            alert($.bsgridLanguage.needInteger);
//        }
//    } else if (parseInt(goPage) < 1 || parseInt(goPage) > options.totalPages) {
//        if (options.settings.pageIncorrectTurnAlert) {
//            alert($.bsgridLanguage.needRange(1, options.totalPages));
//        }
//    } else {
//        $.fn.bsgrid.getGridObj(options.gridId).page(parseInt(goPage));
//    }
//};

//供继承调用服务
$.fn.bsgrid.ex_doServ = function() {
	
}

//供继承调用服务
$.fn.bsgrid.ex_initServ = function() {
	
}


$.fn.bsgrid.init_pagingValues = function(resultObj) {
	
	var params = {};
	var localData = [{}];// 本地测试数据
	params.PAGE_NUMBER = 1;// 获取当前页
	params.PAGE_SIZE = PAGE_SIZE;// 获取分页条数
	
	var totalRows  = resultObj.totalRows;// 总数
	var pageSize  = resultObj.pageSize;// 分页条数
	var tabId = '#'+ resultObj.tabId+"_pt";// grid的id
  	// 请求服务获取数据
  	if (!resultObj.error) {
  	  	var totalPages = parseInt(totalRows / pageSize);// 总页数
  	    totalPages = parseInt((totalRows % pageSize == 0) ? totalPages : totalPages + 1);// 总页数,除不尽时多余一页
  		$(tabId).data("jqPagination").options.max_page = totalPages;
  	    var page_string = $(tabId).data("jqPagination").options.page_string;
  	    page_string = page_string.replace('{current_page}', 1).replace('{max_page}', totalPages + '');
  	    $(tabId + ' input').data('current-page', 1).data('max-page', totalPages).val(page_string);
  		$('#console').html(tabId+''+ $(tabId).html() );
  	}
}


$.fn.bsgrid.page = function (curPage, options) {
    if ($.trim(curPage) == '' || isNaN(curPage)) {
        $.fn.bsgrid.alert($.bsgridLanguage.needInteger);
        return;
    }
    var dataType = options.settings.dataType;
    alert(dataType+'---'+options.settings.localData.success );
    if (options.settings.localData != false) {
    	if (dataType == 'page') {
    		$.fn.bsgrid.loadGridData(dataType, options.settings.localData, options);
    	} else if (dataType == 'json') {
    		$.fn.bsgrid.loadGridData(dataType, options.settings.localData, options);
//            $.fn.bsgrid.loadGridData(dataType, $.fn.bsgrid.buildData.gridData(dataType, curPage, options.settings.localData), options);
        } else if (dataType == 'xml') {
            $.fn.bsgrid.loadGridData(dataType, '<xml>' + $.fn.bsgrid.buildData.gridData(dataType, curPage, options.settings.localData) + '</xml>', options);
        }
        return;
    }
    $.ajax({
        type: options.settings.ajaxType,
        url: options.settings.url,
        data: $.fn.bsgrid.getPageCondition(curPage, options),
        dataType: dataType,
        beforeSend: function (XMLHttpRequest) {
            if (options.settings.isProcessLockScreen) {
                $.fn.bsgrid.lockScreen(options);
            }
            options.settings.beforeSend(options, XMLHttpRequest);
        },
        complete: function (XMLHttpRequest, textStatus) {
            options.settings.complete(options, XMLHttpRequest, textStatus);
            if (options.settings.isProcessLockScreen) {
                $.fn.bsgrid.unlockScreen(options);
            }
        },
        success: function (gridData, textStatus) {
            $.fn.bsgrid.loadGridData(dataType, gridData, options);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.fn.bsgrid.alert($.bsgridLanguage.errorForSendOrRequestData);
        }
    });
}


$.fn.bsgrid.loadGridData = function (dataType, gridData, options) {
    var parseSuccess = $.fn.bsgrid.parseData.success(dataType, gridData);
    alert(parseSuccess);
    for (var key in options.settings.extend.beforeRenderGridMethods) {
        options.settings.extend.beforeRenderGridMethods[key](parseSuccess, gridData, options);
    }
    options.settings.additionalBeforeRenderGrid(parseSuccess, gridData, options);
    if (parseSuccess) {
        // userdata
        var userdata = $.fn.bsgrid.parseData.userdata(dataType, gridData);
        $.fn.bsgrid.storeUserdata(userdata, options);
        options.settings.processUserdata(userdata, options);

        var totalRows = parseInt($.fn.bsgrid.parseData.totalRows(dataType, gridData));
        var curPage = parseInt($.fn.bsgrid.parseData.curPage(dataType, gridData));
        curPage = Math.max(curPage, 1);

        if (options.settings.pageAll) {
            // display all datas, no paging
            curPage = 1;
            options.settings.pageSize = totalRows;
            $('#' + options.noPagingationId).html(totalRows);
        }

        var pageSize = options.settings.pageSize;
        var totalPages = parseInt(totalRows / pageSize);
        totalPages = parseInt((totalRows % pageSize == 0) ? totalPages : totalPages + 1);
        var curPageRowsNum = $.fn.bsgrid.parseData.getDataLen(dataType, gridData);
        curPageRowsNum = curPageRowsNum > pageSize ? pageSize : curPageRowsNum;
        curPageRowsNum = (curPage * pageSize < totalRows) ? curPageRowsNum : (totalRows - (curPage - 1) * pageSize);
        var startRow = (curPage - 1) * pageSize + 1;
        var endRow = startRow + curPageRowsNum - 1;
        startRow = curPageRowsNum <= 0 ? 0 : startRow;
        endRow = curPageRowsNum <= 0 ? 0 : endRow;

        // set options pagination values
        options.totalRows = totalRows;
        options.totalPages = totalPages;
        options.curPage = curPage;
        options.curPageRowsNum = curPageRowsNum;
        options.startRow = startRow;
        options.endRow = endRow;

        if (!options.settings.pageAll) {
            $.fn.bsgrid.setPagingValues(options);
        }

        if (!options.settings.showPageToolbar || (options.settings.displayPagingToolbarOnlyMultiPages && totalPages <= 1)) {
            $('#' + options.pagingId).hide();
            $('#' + options.pagingOutTabId).hide();
        } else {
            $('#' + options.pagingOutTabId).show();
            $('#' + options.pagingId).show();
        }

        $.fn.bsgrid.setGridBlankBody(options);
        if (curPageRowsNum != 0) {
            var data = $.fn.bsgrid.parseData.data(dataType, gridData);
            var dataLen = data.length;
            // add rows click event
            $.fn.bsgrid.addRowsClickEvent(options);
            $.fn.bsgrid.getRows(options).each(
                function (i) {
                    var trObj = $(this);
                    var record = null;
                    if (i < curPageRowsNum && i < dataLen) {
                        // support parse return all datas or only return current page datas
                        record = $.fn.bsgrid.parseData.getRecord(dataType, data, dataLen != totalRows ? i : startRow + i - 1);
                    }
                    $.fn.bsgrid.storeRowData(i, record, options);

                    for (var key in options.settings.extend.renderPerRowMethods) {
                        options.settings.extend.renderPerRowMethods[key](record, i, trObj, options);
                    }
                    options.settings.additionalRenderPerRow(record, i, trObj, options);
                    for (var key in options.settings.event.customRowEvents) {
                        trObj.bind(key, {
                            record: record,
                            rowIndex: i,
                            trObj: trObj,
                            options: options
                        }, function (event) {
                            options.settings.event.customRowEvents[key](event.data.record, event.data.rowIndex, event.data.trObj, event.data.options)
                        });
                    }

                    var columnsModel = options.columnsModel;
                    $(this).find('td').each(function (j) {
                        var tdObj = $(this);
                        if (i < curPageRowsNum && i < dataLen) {
                            // column index
                            var index = columnsModel[j].index;
                            // column render
                            var render = columnsModel[j].render;
                            if (render != '') {
                                var render_method = eval(render);
                                var render_html = render_method(record, i, j, options);
                                tdObj.html(render_html);
                            } else if (index != '') {
                                var value = $.fn.bsgrid.parseData.getColumnValue(dataType, record, index);
                                // column tip
                                if (columnsModel[j].tip == 'true') {
                                    $.fn.bsgrid.columnTip(this, value, record);
                                }
                                if (options.settings.longLengthAotoSubAndTip) {
                                    $.fn.bsgrid.longLengthSubAndTip(this, value, columnsModel[j].maxLen, record);
                                } else {
                                    tdObj.html(value);
                                }
                            }
                        } else {
                            tdObj.html('&nbsp;');
                        }
                        for (var key in options.settings.extend.renderPerColumnMethods) {
                            var renderPerColumn_html = options.settings.extend.renderPerColumnMethods[key](record, i, j, tdObj, trObj, options);
                            if (renderPerColumn_html != null && renderPerColumn_html != false) {
                                tdObj.html(renderPerColumn_html);
                            }
                        }
                        options.settings.additionalRenderPerColumn(record, i, j, tdObj, trObj, options);
                        for (var key in options.settings.event.customCellEvents) {
                            tdObj.bind(key, {
                                record: record,
                                rowIndex: i,
                                colIndex: j,
                                tdObj: tdObj,
                                trObj: trObj,
                                options: options
                            }, function (event) {
                                options.settings.event.customCellEvents[key](event.data.record, event.data.rowIndex, event.data.colIndex, event.data.tdObj, event.data.trObj, event.data.options);
                            });
                        }
                    });
                }
            );
        }
    } else {
        $.fn.bsgrid.alert($.bsgridLanguage.errorForRequestData);
    }
    for (var key in options.settings.extend.afterRenderGridMethods) {
        options.settings.extend.afterRenderGridMethods[key](parseSuccess, gridData, options);
    }
    options.settings.additionalAfterRenderGrid(parseSuccess, gridData, options);
}


//$.fn.bsgrid.buildData = function(type, curPage, data) {
//	alert('5');
//}
//
//
//$.fn.bsgrid.initPaging = function (options) {
//    var pagingSb = new StringBuilder();
//    pagingSb.append('<div id="' + options.pagingId + '" class="pagination">');
//    pagingSb.append('<a href="#" class="first" data-action="first">&laquo;</a>');
//    pagingSb.append('<a href="#" class="previous" data-action="previous">&lsaquo;</a>');
//    pagingSb.append('<input type="text" readonly="readonly" data-max-page="" />');
//    pagingSb.append('<a href="#" class="next" data-action="next">&rsaquo;</a>');
//    pagingSb.append('<a href="#" class="last" data-action="last">&raquo;</a>');
//    pagingSb.append('</div>');
//    $('#' + options.pagingOutTabId + ' td').append(pagingSb.toString());
//
//    $('#' + options.pagingId).jqPagination({
//        current_page: 1,
//        link_string: '#',
//        // max_page: null,
//        // page_string: 'Page {current_page} of {max_page}',
//        /**
//         * The paged callback is called when a valid page request has been made, the page variable simply contains the page requested.
//         */
//        paged: function (page) {
//            // do something with the page variable
//            var result = $.fn.bsgrid.ex_doServ();
//            var localData = "";
//        	// 请求服务获取数据
//        	if (result.success) {
//        		localData = result.data;
//        		 $('#console').html(result.success);
//        	}
////          $.fn.bsgrid.getGridObj(options.gridId).loadGridData('json', localData, options );
//        	
//            $.fn.bsgrid.getGridObj(options.gridId).reloadLocalData( localData );
////            $.fn.bsgrid.getGridObj(options.gridId).page(parseInt(page));
//        }
//    });
//};

//$.fn.bsgrid.initPaging = function (options) {
//    $('#searchTable_pt').jqPagination({
//        current_page: 1,
//        link_string: '#',
//        // max_page: null,
//        // page_string: 'Page {current_page} of {max_page}',
//        /**
//         * The paged callback is called when a valid page request has been made, the page variable simply contains the page requested.
//         */
//        paged: function (page) {
//            // do something with the page variable
//            $.fn.bsgrid.getGridObj(options.gridId).page(parseInt(page));
//        }
//    });
//};


//$.fn.bsgrid.setPagingValues = function (options) {
//    var curPage = options.curPage;
//    var totalRows = options.totalRows;
//    var totalPages = parseInt(totalRows / options.settings.pageSize);
//    totalPages = parseInt((totalRows % options.settings.pageSize == 0) ? totalPages : totalPages + 1);
//    
//    
//    $('#' + options.pagingId).data("jqPagination").options.max_page = totalPages;
//    var page_string = $('#' + options.pagingId).data("jqPagination").options.page_string;
//    page_string = page_string.replace('{current_page}', curPage).replace('{max_page}', totalPages + '');
//    $('#'+options.pagingId+' input').data('current-page', curPage).data('max-page', totalPages).val(page_string);
//};
//
//$.fn.bsgrid.setPagingValues = function (options) {
//    var curPage = options.curPage;
//    var totalRows = options.totalRows;
//    var totalPages = parseInt(totalRows / options.settings.pageSize);
//    totalPages = parseInt((totalRows % options.settings.pageSize == 0) ? totalPages : totalPages + 1);
//
//    $('#' + options.pagingId).data('jqPagination').options.current_page = curPage;
//    $('#' + options.pagingId).data('jqPagination').options.max_page = totalPages;
//    var page_string = $('#' + options.pagingId).data('jqPagination').options.page_string;
//    page_string = page_string.replace('{current_page}', curPage).replace('{max_page}', totalPages + '');
//    $('#' + options.pagingId + ' input').data('current-page', curPage).data('max-page', totalPages).val(page_string);
//    $('#' + options.pagingId).data('jqPagination').setLinks(curPage);
//
//    // page size select
//    if (options.settings.pageSizeSelect) {
//        $('#' + options.pagingId + '_pageSize').remove();
//        $('#' + options.pagingId).prepend('<select id="' + options.pagingId + '_pageSize' + '" style="margin: 1px 0; border-width: 0;"></select>');
//        var optionsSb = new StringBuilder();
//        for (var i = 0; i < options.settings.pageSizeForGrid.length; i++) {
//            var pageVal = options.settings.pageSizeForGrid[i];
//            optionsSb.append('<option value="' + pageVal + '">' + pageVal + '</option>');
//        }
//        $('#' + options.pagingId + '_pageSize').html(optionsSb.toString()).val(options.settings.pageSize);
//        // select change event
//        $('#' + options.pagingId + '_pageSize').change(function () {
//            options.settings.pageSize = parseInt($(this).val());
//            $(this).trigger('blur');
//            // if change pageSize, then page first
//            if (options.curPage == 1) {
//                $.fn.bsgrid.refreshPage(options);
//            } else {
//                $.fn.bsgrid.gotoPage(options, 1);
//            }
//        });
//    }
//};